<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="文件类型" prop="typeId">
        <el-select v-model="queryParams.typeId" placeholder="请选择文件类型">
          <el-option v-for="item in documentTypeList" :key="item.id" :label="item.name" :value="item.id"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="资料名称" prop="name">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入资料名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="文件格式" prop="format">
        <el-input
          v-model="queryParams.format"
          placeholder="请输入文件格式"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
        >新增
        </el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="documentList" x>
      <el-table-column label="文件类型" align="center" >
        <template slot-scope="scope">
          <el-tag type="primary" effect="plain">{{ scope.row.documentType.name }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="资料名称" align="center" prop="name"/>
      <el-table-column label="封面" align="center" prop="image">
        <template slot-scope="scope">
          <el-image :src="scope.row.image" style="width: 100px; height: 100px;"/>
        </template>
      </el-table-column>
      <el-table-column label="文件信息" prop="linkUrl">
        <template slot-scope="scope">
          <el-link icon="el-icon-paperclip" :href="scope.row.linkUrl" type="primary" target="_blank">查看文件</el-link>
            <div style="font-size: 12px; margin-top: 5px;">大小：{{ scope.row.size }}</div>
            <div style="font-size: 12px;">格式：{{ scope.row.format }}</div>
        </template>
      </el-table-column>
      <el-table-column label="上传时间" align="center" prop="createAt"/>
      <el-table-column label="阅读量" align="center" prop="read"/>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
          >修改
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
          >删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改文件对话框 -->
    <el-dialog :title="title" :visible.sync="open" center width="600px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="文件类型" prop="typeId">
          <el-select v-model="form.typeId" placeholder="请选择文件类型">
            <el-option v-for="item in documentTypeList" :key="item.id" :label="item.name" :value="item.id"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="资料名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入资料名称"/>
        </el-form-item>
        <el-form-item label="封面" prop="image">
          <image-upload v-model="form.image"/>
        </el-form-item>
        <el-form-item label="文件上传" prop="linkUrl">
          <el-upload
            drag
            :action="uploadUrl"
            :limit="1"
            accept=".doc,.docx,.pdf,.ppt,.pptx"
            :on-exceed="handleExceed"
            :on-success="handleSuccess"
            :before-upload="handleBeforeUpload"
          >
            <i class="el-icon-upload"></i>
            <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
            <div class="el-upload__tip" slot="tip">只能上传pdf、ppt、pptx、doc、docx格式的文件，且不超过{{ fileSize }}Mb</div>
          </el-upload>
        </el-form-item>
        <el-form-item label="文件大小" prop="size">
          <el-input v-model="form.size" disabled placeholder="请输入文件大小"/>
        </el-form-item>
        <el-form-item label="文件格式" prop="format">
          <el-input v-model="form.format" disabled placeholder="请输入文件格式"/>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" size="small" @click="submitForm">确 定</el-button>
        <el-button @click="cancel" size="small">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listDocument, getDocument, delDocument, addDocument, updateDocument } from '@/api/app/document'
import { listType } from '@/api/app/document-type'
export default {
  name: 'Document',
  data() {
    return {
      uploadUrl: process.env.VUE_APP_BASE_API + '/upload/oss', // 上传的服务器地址
      fileSize: 10, // 文件大小限制，单位：MB
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 文件表格数据
      documentList: [],
      // 弹出层标题
      title: '',
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        typeId: null,
        name: null,
        format: null
      },
      documentTypeList: [],
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        typeId: [
          { required: true, message: '文件类型不能为空', trigger: 'blur' }
        ],
        name: [
          { required: true, message: '资料名称不能为空', trigger: 'blur' }
        ],
        image: [
          { required: true, message: '封面不能为空', trigger: 'blur' }
        ],
        linkUrl: [
          { required: true, message: '文件链接不能为空', trigger: 'blur' }
        ],
        size: [
          { required: true, message: '文件大小不能为空', trigger: 'blur' }
        ],
        format: [
          { required: true, message: '文件格式不能为空', trigger: 'blur' }
        ]
      }
    }
  },
  created() {
    this.getList()
    this.getDocumentTypeList()
  },
  methods: {
    /** 查询文件列表 */
    getList() {
      this.loading = true
      listDocument(this.queryParams).then(response => {
        this.documentList = response.rows
        this.total = response.total
        this.loading = false
      })
    },

    getDocumentTypeList() {
      listType({
        pageSize: 20
      }).then(response => {
        this.documentTypeList = response.rows
      })
    },

    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        typeId: null,
        name: null,
        image: null,
        linkUrl: null,
        size: null,
        format: null
      }
      this.resetForm('form')
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm('queryForm')
      this.handleQuery()
    },

    /** 新增按钮操作 */
    handleAdd() {
      this.reset()
      this.open = true
      this.title = '添加文件'
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset()
      const id = row.id || this.ids
      getDocument(id).then(response => {
        this.form = response.data
        this.open = true
        this.title = '修改文件'
      })
    },

    handleBeforeUpload(file) {
      if (this.fileSize) {
        const isLt = file.size / 1024 / 1024 < this.fileSize;
        if (!isLt) {
          this.$modal.msgError(`上传的文件大小不能超过 ${this.fileSize} MB!`);
          return false;
        }
      }
    },

    handleExceed(files, file) {
      this.$modal.msgError(`上传文件数量不能超过 1 个!`)
    },
    // 上传成功回调
    handleSuccess(res, file) {
      this.form.linkUrl = res.data.url
      this.form.size = res.data.fileSize
      this.form.format = res.data.suffix // 文件格式
    },

    /** 提交按钮 */
    submitForm() {
      this.$refs['form'].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateDocument(this.form).then(response => {
              this.$modal.msgSuccess('修改成功')
              this.open = false
              this.getList()
            })
          } else {
            addDocument(this.form).then(response => {
              this.$modal.msgSuccess('新增成功')
              this.open = false
              this.getList()
            })
          }
        }
      })
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids
      this.$modal.confirm('是否确认删除文件编号为"' + ids + '"的数据项？').then(function() {
        return delDocument(ids)
      }).then(() => {
        this.getList()
        this.$modal.msgSuccess('删除成功')
      }).catch(() => {
      })
    }
  }
}
</script>
